<template>
  <div class="login-container">
    <div class="login-card">
      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 登录Tab -->
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="auth-form">
            <el-form-item prop="username">
              <div class="form-label">用户名</div>
              <el-input 
                v-model="loginForm.username" 
                placeholder="请输入用户名" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <div class="form-label">密码</div>
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码" 
                size="large"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            
            <div class="forgot-password">
              <span>忘记密码?</span>
            </div>
            
            <el-form-item>
              <el-button 
                class="submit-button" 
                size="large" 
                :loading="loginLoading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 注册Tab -->
        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="auth-form">
            <el-form-item prop="username">
              <div class="form-label">用户名</div>
              <el-input 
                v-model="registerForm.username" 
                placeholder="请输入用户名" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="email">
              <div class="form-label">邮箱（可选）</div>
              <el-input 
                v-model="registerForm.email" 
                placeholder="请输入邮箱" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <div class="form-label">密码</div>
              <el-input 
                v-model="registerForm.password" 
                type="password" 
                placeholder="请输入密码（至少6位）" 
                size="large"
                show-password
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <div class="form-label">确认密码</div>
              <el-input 
                v-model="registerForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入密码" 
                size="large"
                show-password
                @keyup.enter="handleRegister"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button 
                class="submit-button" 
                size="large" 
                :loading="registerLoading"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api'

const router = useRouter()
const activeTab = ref('login')
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const loginLoading = ref(false)
const registerLoading = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度至少3位', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loginLoading.value = true
    try {
      const response = await authAPI.login({
        username: loginForm.username,
        password: loginForm.password
      })
      
      // 保存token
      localStorage.setItem('access_token', response.tokens.access)
      localStorage.setItem('refresh_token', response.tokens.refresh)
      localStorage.setItem('user_info', JSON.stringify(response.user))
      
      ElMessage.success('登录成功')
      
      // 跳转到主页
      router.push('/')
    } catch (error) {
      console.error('登录错误详情:', error)
      console.error('错误响应:', error.response)
      console.error('错误数据:', error.response?.data)
      const errorMsg = error.response?.data?.error || error.message || '登录失败'
      ElMessage.error(errorMsg)
    } finally {
      loginLoading.value = false
    }
  })
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    registerLoading.value = true
    try {
      const response = await authAPI.register({
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password
      })
      
      // 保存token
      localStorage.setItem('access_token', response.tokens.access)
      localStorage.setItem('refresh_token', response.tokens.refresh)
      localStorage.setItem('user_info', JSON.stringify(response.user))
      
      ElMessage.success('注册成功')
      
      // 跳转到主页
      router.push('/')
    } catch (error) {
      console.error('注册错误详情:', error)
      console.error('错误响应:', error.response)
      console.error('错误数据:', error.response?.data)
      const errorMsg = error.response?.data?.error || error.message || '注册失败'
      ElMessage.error(errorMsg)
    } finally {
      registerLoading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
  background: url('https://haowallpaper.com/link/common/file/previewFileImg/17469681190358400') center/cover no-repeat;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  pointer-events: none;
}

.login-card {
  width: 450px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px 45px;
  box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
}

.login-tabs {
  margin-bottom: 10px;
}

.auth-form {
  margin-top: 25px;
}

.form-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
  font-weight: 500;
}

.forgot-password {
  text-align: center;
  margin: 15px 0 25px 0;
}

.forgot-password span {
  color: #666;
  font-size: 13px;
  cursor: pointer;
  transition: color 0.3s;
}

.forgot-password span:hover {
  color: #ff8c42;
}

.submit-button {
  width: 100%;
  background: linear-gradient(135deg, #ff8c42 0%, #ff6b35 100%);
  border: none;
  border-radius: 10px;
  color: white;
  font-size: 16px;
  font-weight: 500;
  height: 45px;
  transition: all 0.3s;
}

.submit-button:hover {
  background: linear-gradient(135deg, #ff7a2e 0%, #ff5521 100%);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 107, 53, 0.4);
}

:deep(.el-tabs__header) {
  margin: 0 0 20px 0;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #e4e7ed;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  color: #909399;
  padding: 0 30px;
}

:deep(.el-tabs__item.is-active) {
  color: #ff8c42;
}

:deep(.el-tabs__active-bar) {
  background-color: #ff8c42;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-input__wrapper) {
  background: #f8f9fa;
  box-shadow: none;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 10px 15px;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  border-color: #ff8c42;
}

:deep(.el-input__wrapper.is-focus) {
  background: #fff;
  border-color: #ff8c42;
  box-shadow: 0 0 0 2px rgba(255, 140, 66, 0.1);
}

:deep(.el-input__inner) {
  color: #333;
}

:deep(.el-input__inner::placeholder) {
  color: #c0c4cc;
}
</style>
